/*
 *所有关于Tb_Project_Fundtemplate类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*Tb_Project_FundtemplateService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using MYData.Entity.DomainModels;
using MYData.Core.Utilities;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using MYData.System.IRepositories;
using System.Threading.Tasks;
using Mapster;
using MYData.Core.EFDbContext;
using MYData.Entity.DTO.ApiEntity.Input;
using MYData.Core.Enums;
using System.Collections.Generic;
using Snowflake.Core;

namespace MYData.System.Services
{
    public partial class Tb_Project_FundtemplateService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ITb_Project_FundtemplateRepository _repository;//访问数据库
        private readonly VOLContext _context;

        [ActivatorUtilitiesConstructor]
        public Tb_Project_FundtemplateService(
            ITb_Project_FundtemplateRepository dbRepository,
            IHttpContextAccessor httpContextAccessor
,
            VOLContext context)
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            _context = context;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }

        WebResponseContent webResponse = new WebResponseContent();

        /// <summary>
        /// 添加项目经费模板(事务)
        /// MJZ 2023/4/1 20:42
        /// </summary>
        /// <returns></returns>
        public WebResponseContent InsertFundingTemplateAsync(ProjectFundingTemplateInput_Dto inputDto)
        {
            //开启事务   
            _context.Database.BeginTransaction();
            try
            {
                //预算模板实体转换
                var Entity = inputDto.Adapt<Tb_Project_Fundtemplate>();
                //Entity.fundtemplateId=new IdWorker(1,1).NextId().ToString();
                //项目来源单位实体转换 
                var model = inputDto.Source.Adapt<tb_project_fundingtemplatesource_relation>();
                model.templateId = Entity.fundtemplateId;
                //模板与经费科目关系表的添加
                List<Tb_Project_Templatesubject_Relationship> tb_project_templatesubject_relationship = new List<Tb_Project_Templatesubject_Relationship>();
                //实例化直接经费的关系表
                tb_project_templatesubject_relationship.Add(new Tb_Project_Templatesubject_Relationship
                {
                    fundtemplateId = Entity.fundtemplateId,
                    supportingBudgetId = "##",
                    supportingBudgetTypeId = true
                });
                //实例化间接经费的关系表
                tb_project_templatesubject_relationship.Add(new Tb_Project_Templatesubject_Relationship
                {
                    fundtemplateId = Entity.fundtemplateId,
                    supportingBudgetId = "##",
                    supportingBudgetTypeId = false
                });
                //项目来源单位添加
                _context.Set<Tb_Project_Fundtemplate>().Add(Entity);
                if (_context.SaveChanges() < 1)
                {
                    //主表添加失败  事务回滚
                    _context.Database.RollbackTransaction();
                    return webResponse.Error("主表添加失败！！！");
                }
                //预算模板添加
                _context.Set<tb_project_fundingtemplatesource_relation>().Add(model);
                if (_context.SaveChanges() < 1)
                {
                    //预算模板表添加失败  事务回滚
                    _context.Database.RollbackTransaction();
                    return webResponse.Error("预算科目添加失败！！！");
                }
                //模板与经费科目关系表的添加
                _context.Set<Tb_Project_Templatesubject_Relationship>().AddRange(tb_project_templatesubject_relationship);
                _context.SaveChanges();
                //提交事务
                _context.Database.CommitTransaction();
                // 保存更改并返回成功响应
                return webResponse.OK("添加模板成功！", true);
            }
            catch (global::System.Exception)
            {
                _context.Database.RollbackTransaction();
                return webResponse.Error("添加失败！！！");
            }
        }

        /// <summary>
        /// 删除项目经费模板(逻辑删除)
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<WebResponseContent> SoftDeleteFundingTemplateAsync(string fundtemplateId)
        {
            //通过模板Id查询到实体
            var model = _context.Set<Tb_Project_Fundtemplate>().Find(fundtemplateId);
            //对实体的是否删除字段进行更改
            model.isDelete = 1;
            //提交更改
            _repository.Update(model);
            //返回成功信息
            return webResponse.OK("删除成功!", await _repository.SaveChangesAsync());
        }

        /// <summary>
        /// 删除项目经费模板(物理删除)
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<WebResponseContent> DeleteFundingTemplateAsync(string Id)
        {
            var model = _context.Set<Tb_Project_Fundtemplate>().Find(Id);
            _repository.Delete(model);
            return webResponse.OK("删除成功!", await _repository.SaveChangesAsync());
        }

        /// <summary>
        /// 修改项目经费模板
        /// </summary>
        /// <returns></returns>
        public async Task<WebResponseContent> UpdateFundingTemplateAsync(UpdateTemplateSource_Dto inputDto)
        {
            //Automapper实体转换
            var Entity = inputDto.Adapt<Tb_Project_Fundtemplate>();
            _repository.Update(Entity);
            return webResponse.OK("修改模板成功!", await _repository.SaveChangesAsync());
        }
    }
}
